/*
 * uart_data_transmission.c
 *
 *  Created on: Jun 27, 2025
 *      Author:
 */


#include "stm32f1xx_hal.h"
#include <stdio.h>
#include <string.h>
#include <main.h>
#include <stdlib.h>
#include <uart_data_transmission.h>
#include "oled.h"
#include "numtostr.h"
#include "adc_read.h"

// uart_data_transmission.c
extern UART_HandleTypeDef huart1;  //


#define MAX_RESPONSE_LENGTH 100
char responseBuffer[MAX_RESPONSE_LENGTH];
uint8_t responseIndex = 0;
uint8_t responseComplete = 0;
uint8_t u_rxData;  //
uint8_t read_5 = 0;//




void get_result_s300(SensorData* sensorData){
	char response[MAX_RESPONSE_LENGTH];
	char res_1[MAX_RESPONSE_LENGTH];
	char* command = "$R001\r\n";
	char* connect_command = "$R009\r\n";
	uint8_t if_ok = 0;
	if(read_5 > 5){
		if_ok = 1;
	}
	else {
		if_ok = sendCommandAndReceiveResponse(connect_command, res_1, MAX_RESPONSE_LENGTH,200);
		HAL_Delay(100); //
	}
	if(if_ok > 0){
		read_5 += 1;
	if(sendCommandAndReceiveResponse(command, response, MAX_RESPONSE_LENGTH,100)> 0){
	parseResponse(response, sensorData);
	}
	else{
		read_5 = 0;
	}
	}
}


void show_tmps(SensorData* sensorData,uint8_t if_need_chk,I2C_HandleTypeDef *hi2c){
	char c_temperature[10];
	char c_par[10];
	char c_humidity[10];
	uint32_t sensor_r = Sensor_ReadPPM();
	if(if_need_chk < 15000){
	  //wait for heat
	  sensor_r = 0;
	  }
	sensorData->particleConcentration = sensorData->particleConcentration>sensor_r?sensorData->particleConcentration:sensor_r;
	/* number to string */
	IntToStr(sensorData->particleConcentration,c_par,5);
	FloatToStr((float)sensorData->temperature/10.0f,c_temperature,1,3,0);
	FloatToStr((float)sensorData->humidity/10.0f,c_humidity,1,3,0);
	/* number to string */
	/* show words */
	char s_par[15] = "PPM:";
	strcat(s_par,c_par);
	OLED_DisplayStringCentered(hi2c,0,s_par);
	char s_tem[10] = "温度:";
	strcat(s_tem,c_temperature);
	strcat(s_tem,"°C");
	OLED_DisplayStringCentered(hi2c,1,s_tem);
	char s_hum[10] = "湿度:";
	strcat(s_hum,c_humidity);
	strcat(s_hum,"%");
	OLED_DisplayStringCentered(hi2c,2,s_hum);
}

//
void ClearUARTBuffer(UART_HandleTypeDef *huart) {
    uint32_t tmp;

    //
    while (__HAL_UART_GET_FLAG(huart, UART_FLAG_RXNE) != RESET) {
        tmp = huart->Instance->SR;  //
        tmp = huart->Instance->DR;  //
        (void)tmp;  //
    }
}


uint8_t sendCommandAndReceiveResponse(char* command, char* response, uint16_t maxLength, int delay_tm)
{
    HAL_StatusTypeDef status;
    responseIndex = 0;
    responseComplete = 0;
    ClearUARTBuffer(&huart1);

    status = HAL_UART_Transmit(&huart1, (uint8_t*)command, strlen(command), 100);
    if (status != HAL_OK) {

        return 0;
    }


    status = HAL_UART_Receive_IT(&huart1, &u_rxData, 1);



    uint32_t startTime = HAL_GetTick();
    while (!responseComplete && (HAL_GetTick() - startTime) < delay_tm) {

        HAL_Delay(1);
    }


    if (!responseComplete) {

        return 0;
    }


    if (responseIndex < maxLength - 1) {
        responseBuffer[responseIndex] = '\0';
        strncpy(response, responseBuffer, maxLength);
        return 1;
    } else {
        response[maxLength - 1] = '\0';
        strncpy(response, responseBuffer, maxLength);
        return 0;
    }
}

uint8_t parseResponse(const char* response, SensorData* data)
{
    if (strncmp(response, "$DATA,", 6) != 0) {
        memset(data, 0, sizeof(SensorData));
        data->isValid = 0;
    }


   memset(data, 0, sizeof(SensorData));
    data->isValid = 1;


    char* token = strtok((char*)response + 6, ",");


       for (int i = 0; i < 3; i++) {
           if (token != NULL) {
               token = strtok(NULL, ",");
           } else {
               data->isValid = 0;
           }
       }

    if (token != NULL) {
        data->particleConcentration = atoi(token);
    } else {
        data->isValid = 0;
    }

    token = strtok(NULL, ",");
    if (token != NULL) {
        data->temperature = atoi(token);
    } else {
        data->isValid = 0;
    }

    token = strtok(NULL, ",");
    if (token != NULL) {
        data->humidity = atoi(token);
    } else {
        data->isValid = 0;
    }

    return data->isValid;
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
    if (huart->Instance == USART1) {
        if (responseIndex < MAX_RESPONSE_LENGTH - 1) {
            responseBuffer[responseIndex++] = u_rxData;

            if (u_rxData == '\n') {
                responseComplete = 1;
            }
        } else {
            responseComplete = 1;
        }

        HAL_UART_Receive_IT(&huart1, &u_rxData, 1);
    }
}
